"""
用户认证管理模块
"""

import hashlib
import secrets
import time
from typing import Optional, Dict, Any
from .session_manager import SessionManager

class AuthManager:
    """用户认证管理器"""
    
    def __init__(self, storage_manager):
        """初始化认证管理器"""
        self.storage_manager = storage_manager
        self.session_manager = SessionManager()
        self.current_user = None
        
        # 初始化系统用户表
        self._init_system_tables()
    
    def _init_system_tables(self):
        """初始化系统表"""
        # 检查系统用户表是否存在
        if not self.storage_manager.table_exists('system_users'):
            self._create_system_users_table()
        
        # 检查权限表是否存在
        if not self.storage_manager.table_exists('table_permissions'):
            self._create_permissions_table()
        
        # 检查系统目录表是否存在
        if not self.storage_manager.table_exists('system_catalog'):
            self._create_system_catalog_table()
        
        # 创建默认管理员用户
        self._create_default_admin()
    
    def _create_system_users_table(self):
        """创建系统用户表"""
        schema = {
            'columns': {
                'user_id': {'type': {'type': 'int'}, 'primary_key': True},
                'username': {'type': {'type': 'varchar', 'length': 50}, 'unique': True},
                'password_hash': {'type': {'type': 'varchar', 'length': 255}},
                'role': {'type': {'type': 'varchar', 'length': 20}},
                'created_at': {'type': {'type': 'varchar', 'length': 50}},
                'is_active': {'type': {'type': 'int'}}  # 0: inactive, 1: active
            },
            'primary_key': 'user_id'
        }
        
        self.storage_manager.create_table('system_users', schema)
    
    def _create_permissions_table(self):
        """创建权限表"""
        schema = {
            'columns': {
                'table_name': {'type': {'type': 'varchar', 'length': 100}},
                'user_id': {'type': {'type': 'int'}},
                'permission_type': {'type': {'type': 'varchar', 'length': 20}},
                'granted_by': {'type': {'type': 'int'}},
                'granted_at': {'type': {'type': 'varchar', 'length': 50}}
            }
        }
        
        self.storage_manager.create_table('table_permissions', schema)
    
    def _create_system_catalog_table(self):
        """创建系统目录表"""
        schema = {
            'columns': {
                'table_name': {'type': {'type': 'varchar', 'length': 100}, 'primary_key': True},
                'owner_id': {'type': {'type': 'int'}},
                'created_at': {'type': {'type': 'varchar', 'length': 50}},
                'permissions': {'type': {'type': 'varchar', 'length': 500}}  # JSON字符串
            },
            'primary_key': 'table_name'
        }
        
        self.storage_manager.create_table('system_catalog', schema)
    
    def _create_default_admin(self):
        """创建默认管理员用户"""
        # 检查是否已有管理员用户
        admin_users = self.storage_manager.query_table(
            'system_users', 
            {'role': 'admin', 'is_active': 1}
        )
        
        if not admin_users:
            # 创建默认管理员
            admin_password = 'admin123'  # 默认密码
            password_hash = self._hash_password(admin_password)
            
            admin_user = {
                'user_id': 1,
                'username': 'admin',
                'password_hash': password_hash,
                'role': 'admin',
                'created_at': str(int(time.time())),
                'is_active': 1
            }
            
            self.storage_manager.insert_record('system_users', admin_user)
            print("已创建默认管理员用户: admin/admin123")
    
    def _hash_password(self, password: str) -> str:
        """哈希密码"""
        # 使用SHA-256加盐哈希
        salt = secrets.token_hex(16)
        hash_obj = hashlib.sha256()
        hash_obj.update((password + salt).encode('utf-8'))
        return f"{salt}:{hash_obj.hexdigest()}"
    
    def _verify_password(self, password: str, password_hash: str) -> bool:
        """验证密码"""
        try:
            salt, hash_value = password_hash.split(':')
            hash_obj = hashlib.sha256()
            hash_obj.update((password + salt).encode('utf-8'))
            return hash_obj.hexdigest() == hash_value
        except:
            return False
    
    def login(self, username: str, password: str) -> bool:
        """用户登录"""
        try:
            # 查询用户
            users = self.storage_manager.query_table(
                'system_users',
                {'username': username, 'is_active': 1}
            )
            
            if not users:
                return False
            
            user = users[0]
            
            # 验证密码
            if not self._verify_password(password, user['password_hash']):
                return False
            
            # 创建会话
            session_id = self.session_manager.create_session(user['user_id'])
            self.current_user = {
                'user_id': user['user_id'],
                'username': user['username'],
                'role': user['role'],
                'session_id': session_id
            }
            
            return True
            
        except Exception as e:
            print(f"登录错误: {e}")
            return False
    
    def logout(self) -> bool:
        """用户登出"""
        if self.current_user:
            self.session_manager.destroy_session(self.current_user['session_id'])
            self.current_user = None
            return True
        return False
    
    def is_authenticated(self) -> bool:
        """检查是否已认证"""
        if not self.current_user:
            return False
        
        # 验证会话是否有效
        return self.session_manager.validate_session(self.current_user['session_id'])
    
    def get_current_user(self) -> Optional[Dict[str, Any]]:
        """获取当前用户信息"""
        if self.is_authenticated():
            return self.current_user
        return None
    
    def create_user(self, username: str, password: str, role: str = 'user') -> bool:
        """创建新用户（仅管理员可用）"""
        if not self.is_authenticated() or self.current_user['role'] != 'admin':
            return False
        
        try:
            # 检查用户名是否已存在
            existing_users = self.storage_manager.query_table(
                'system_users',
                {'username': username}
            )
            
            if existing_users:
                return False
            
            # 获取下一个用户ID
            all_users = self.storage_manager.query_table('system_users', {})
            next_user_id = max([u['user_id'] for u in all_users], default=0) + 1
            
            # 创建用户
            password_hash = self._hash_password(password)
            new_user = {
                'user_id': next_user_id,
                'username': username,
                'password_hash': password_hash,
                'role': role,
                'created_at': str(int(time.time())),
                'is_active': 1
            }
            
            self.storage_manager.insert_record('system_users', new_user)
            return True
            
        except Exception as e:
            print(f"创建用户错误: {e}")
            return False
    
    def change_password(self, old_password: str, new_password: str) -> bool:
        """修改密码"""
        if not self.is_authenticated():
            return False
        
        try:
            # 获取当前用户信息
            users = self.storage_manager.query_table(
                'system_users',
                {'user_id': self.current_user['user_id']}
            )
            
            if not users:
                return False
            
            user = users[0]
            
            # 验证旧密码
            if not self._verify_password(old_password, user['password_hash']):
                return False
            
            # 更新密码
            new_password_hash = self._hash_password(new_password)
            self.storage_manager.update_record(
                'system_users',
                {'user_id': self.current_user['user_id']},
                {'password_hash': new_password_hash}
            )
            
            return True
            
        except Exception as e:
            print(f"修改密码错误: {e}")
            return False
    
    def list_users(self) -> list:
        """列出所有用户（仅管理员可用）"""
        if not self.is_authenticated() or self.current_user['role'] != 'admin':
            return []
        
        try:
            users = self.storage_manager.query_table('system_users', {})
            # 不返回密码哈希
            for user in users:
                del user['password_hash']
            return users
        except:
            return []
    
    def deactivate_user(self, user_id: int) -> bool:
        """停用用户（仅管理员可用）"""
        if not self.is_authenticated() or self.current_user['role'] != 'admin':
            return False
        
        try:
            self.storage_manager.update_record(
                'system_users',
                {'user_id': user_id},
                {'is_active': 0}
            )
            return True
        except:
            return False
